﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;

using MM.Entities;
using MM.Business;

using System.Devices;// rapi2.dll

namespace MM
{
    public partial class frmTaoPhieuCK : Form
    {
        string _matau = "";
        string _nguoitao = "";
        string _sConn = "";
        string _plant = "";
        List<CHI_TIET_PCK> lstCK = new List<CHI_TIET_PCK>();
        public List<VAT_TU_PHU_TUNG> lstVTPT = new List<VAT_TU_PHU_TUNG>();
        frmTimKiemVTPT frm;
        frmTimKiemTheoHinh frm1;
        frmImpa_TimKiem frm2;
        frmImpa_TimKiemTheoHinh frm3;

        public frmTaoPhieuCK(string sConn)
        {
            InitializeComponent();
            _sConn = sConn;

            _matau = frmDangNhap.objTau._tenTau2KiTu;
            _nguoitao = frmDangNhap.objTaiKhoan._soCMND;
            _plant = frmDangNhap.objTau._plantReferenceSAP;


            this.txtNgayThucHien.Text = DateTime.Today.Day.ToString() + "/" + DateTime.Today.Month.ToString() + "/" + DateTime.Today.Year.ToString();
            this.txtNguoiThucHien.Text = _nguoitao;
            this.InitKhoDich();
            this.gridControl1.DataSource = lstCK;
            frm = new frmTimKiemVTPT(_sConn);
        }

        private void InitKho(string mavtpt)
        {
            clsKHO khoCtrl = new clsKHO(_sConn);
            List<KHO> lst = new List<KHO>();
            lst = khoCtrl.usp_SelectKHO_ByMaVTPT_TON_KHO(mavtpt);
            this.lookUpKho.Properties.DataSource = lst;
            this.lookUpKho.Properties.DisplayMember = "TenKho";
            this.lookUpKho.Properties.ValueMember = "MaKho";
        }

        private void InitKhoDich()
        {
            clsKHO khoCtrl = new clsKHO(_sConn);
            List<KHO> lst = new List<KHO>();
            lst = khoCtrl.LoadKHOByTAU(_matau);
            this.lookUpKhoDich.Properties.DataSource = lst;
            this.lookUpKhoDich.Properties.DisplayMember = "TenKho";
            this.lookUpKhoDich.Properties.ValueMember = "MaKho";
        }

        private void InitTrangthai(string mavtpt, string makho)
        {
            clsTRANG_THAI_VTPT ttCtrl = new clsTRANG_THAI_VTPT(_sConn);
            List<TRANG_THAI_VTPT> lst = new List<TRANG_THAI_VTPT>();
            lst = ttCtrl.usp_SelectTRANG_THAI_VTPTByMaVTPT_TON_KHO(mavtpt, makho);
            this.lookUpTrangthai.Properties.DataSource = lst;
            this.lookUpTrangthai.Properties.DisplayMember = "TenTrangThai";
            this.lookUpTrangthai.Properties.ValueMember = "MaTrangThai";
            if (lst.Count > 0)
            {
                this.lookUpTrangthai.Properties.ForceInitialize();
                this.lookUpTrangthai.ItemIndex = 0;
            }
        }


        private void cmdTimVTPT_Click(object sender, EventArgs e)
        {
            lstVTPT.Clear();

            frm.SelectLstMaterial += new frmTimKiemVTPT.SelectListMaterialHandler(LuuDSVTPT);
            frm.ShowDialog();
        }
        private void LuuDSVTPT(object sender, lstVtptEventArgs e)
        {
            lstVTPT = e.lstVtpt;
            //if (lstVTPT.Count > 0)
            //{
            //    this.txtMaVTPT.Text = lstVTPT[0]._maVTPT;
            //    this.lblTenVTPT.Text = lstVTPT[0]._tenVTPT;
            //}
        }

        private void lookUpKho_QueryPopUp(object sender, CancelEventArgs e)
        {
            try
            {
                this.InitKho(this.txtMaVTPT.Text);
                VAT_TU_PHU_TUNG obj = new VAT_TU_PHU_TUNG();

                clsVAT_TU_PHU_TUNG vtptCtrl = new clsVAT_TU_PHU_TUNG(_sConn);

                obj = vtptCtrl.SelectVAT_TU_PHU_TUNG(this.txtMaVTPT.Text.Trim(),frmDangNhap.objTau.maTau);
                if (obj != null && obj._maVTPT != "")
                {
                    this.lblTenVTPT.Text = obj._tenVTPT;
                }

                if (lookUpTrangthai.Text != "")
                    lookUpTrangthai.ItemIndex = 0;
            }
            catch { }
        }

        private void lookUpTrangthai_QueryPopUp(object sender, CancelEventArgs e)
        {
            try
            {
                string makho = this.lookUpKho.GetColumnValue("MaKho").ToString();
                this.InitTrangthai(this.txtMaVTPT.Text, makho);
            }
            catch { }
        }

        private void lookUpTrangthai_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            try
            {
                string matrangthai = this.lookUpTrangthai.GetColumnValue("MaTrangThai").ToString().Trim();
                string makho = this.lookUpKho.GetColumnValue("MaKho").ToString();
                string mavtpt = this.txtMaVTPT.Text;
                if (makho != "" && (matrangthai != "" || matrangthai != "-1"))
                {
                    this.txtSoLuong.Enabled = true;
                    clsTON_KHO tonCtrl = new clsTON_KHO(_sConn);
                    List<TON_KHO> lstton = new List<TON_KHO>();
                    lstton = tonCtrl.usp_SelectTON_KHO_ByMaKho(makho, mavtpt, int.Parse(matrangthai), null, null);
                    float soluongmax = 0;
                    for (int i = 0; i < lstton.Count; i++)
                    {
                        soluongmax += lstton[i].SoLuong;
                    }


                    // kiem tra xem VTPT nay co cac phieu xuat kho nao chua duoc duyet
                    List<CHI_TIET_PXH> lstctpxh = new List<CHI_TIET_PXH>();
                    clsCHI_TIET_PXH ctpxhCtrl = new clsCHI_TIET_PXH(_sConn);
                    lstctpxh = ctpxhCtrl.usp_CheckSoLuongXuatKhoChuaDuyet(mavtpt, makho, int.Parse(matrangthai));
                    for (int i = 0; i < lstctpxh.Count; i++)
                    {
                        soluongmax -= lstctpxh[i].SoLuong;
                    }

                    // kiem tra xem VTPT nay da ton tai trong list can chuyen kho chua
                    for (int i = 0; i < lstCK.Count; i++)
                    {
                        if (lstCK[i].MaThietBi == mavtpt && lstCK[i].MaKhoNguon == makho && lstCK[i].MaTrangThai == int.Parse(matrangthai))
                            soluongmax -= lstCK[i].SoLuong;
                    }

                    this.lblsoluongton.Text = soluongmax.ToString();
                    this.cmdThemDS.Enabled = true;
                }
                else
                {
                    this.txtSoLuong.Enabled = false;
                    this.lblsoluongton.Text = "0";
                }
            }
            catch { }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string khonguon = this.lookUpKho.GetColumnValue("MaKho").ToString();
                string khodich = this.lookUpKhoDich.GetColumnValue("MaKho").ToString();
                if (khonguon == "" || khodich == "")
                {
                    MessageBox.Show("VUI LÒNG CHỌN ĐẦY ĐỦ KHO NGUỒN VÀ KHO ĐÍCH");
                    return;
                }
                if (khonguon == khodich)
                {
                    MessageBox.Show("KHO ĐÍCH PHẢI KHÁC KHO NGUỒN");
                    return;
                }
                int matrangthai = int.Parse(this.lookUpTrangthai.GetColumnValue("MaTrangThai").ToString());
                if (matrangthai == -1)
                {
                    MessageBox.Show("VUI LÒNG CHỌN TRẠNG THÁI CHO VTPT CẦN CHUYỂN KHO");
                    return;
                }
                float soluongmax = float.Parse(this.lblsoluongton.Text.Trim());
                float soluong = float.Parse(this.txtSoLuong.Text.Trim());

                if (soluong <= 0)
                {
                    MessageBox.Show("VUI LÒNG NHẬP SỐ LƯỢNG > 0");
                    return;
                }

                if (soluong > soluongmax)
                {
                    MessageBox.Show("VUI LÒNG NHẬP SỐ LƯỢNG CHUYỂN KHO <= " + this.lblsoluongton.Text);
                    return;
                }

                // kiem tra vtpt
                VAT_TU_PHU_TUNG obj = new VAT_TU_PHU_TUNG();

                clsVAT_TU_PHU_TUNG vtptCtrl = new clsVAT_TU_PHU_TUNG(_sConn);

                obj = vtptCtrl.SelectVAT_TU_PHU_TUNG(this.txtMaVTPT.Text.Trim(), frmDangNhap.objTau.maTau);
                if (obj != null && obj._maVTPT != "")
                {
                    this.lblTenVTPT.Text = obj._tenVTPT;
                    this.cmdCapNhatSL.Enabled = true;
                    this.cmdThemDS.Enabled = true;
                    this.cmdXoaVTPT.Enabled = true;
                }
                else
                {
                    this.cmdCapNhatSL.Enabled = false;
                    this.cmdThemDS.Enabled = false;
                    this.cmdXoaVTPT.Enabled = false;

                    MessageBox.Show("KHÔNG TÌM THẤY THÔNG TIN VẬT TƯ NÀY");
                }
                // end kiem tra vtpt

                CHI_TIET_PCK objPCK = new CHI_TIET_PCK();
                objPCK.MaKhoDich = khodich;
                objPCK.MaKhoNguon = khonguon;
                objPCK.MaThietBi = this.txtMaVTPT.Text;
                objPCK.TenVTPT = this.lblTenVTPT.Text;
                objPCK.SoLuong = soluong;
                objPCK.MaTrangThai = matrangthai;
                objPCK.TenTrangThai = this.lookUpTrangthai.GetColumnValue("TenTrangThai").ToString();

                int k=lstCK.FindIndex(delegate (CHI_TIET_PCK x) {return (x.MaThietBi==objPCK.MaThietBi && x.MaTrangThai==objPCK.MaTrangThai && x.MaKhoNguon==objPCK.MaKhoNguon && x.MaKhoDich==objPCK.MaKhoDich);});
                if (k<0)
                    lstCK.Add(objPCK);
                else
                    lstCK[k].SoLuong+=objPCK.SoLuong;

                this.gridControl1.DataSource = lstCK;
                this.gridControl1.RefreshDataSource();

                soluongmax -= soluong;
                this.lblsoluongton.Text = soluongmax.ToString();

                if (lstVTPT.Count > 0)
                {
                    lstVTPT.RemoveAt(0);
                    if (lstVTPT.Count > 0)
                    {
                        this.txtMaVTPT.Text = lstVTPT[0]._maVTPT;
                        this.lblTenVTPT.Text = lstVTPT[0]._tenVTPT;
                    }
                }

                this.lookUpTrangthai.ItemIndex = 0;
            }
            catch { MessageBox.Show("CHƯA NHẬP DỮ LIỆU ĐẦY ĐỦ VÀ HỢP LỆ"); }
        }

        private void txtMaVTPT_TextChanged(object sender, EventArgs e)
        {
            this.InitKho("");
            this.InitTrangthai("", "");
            this.lblsoluongton.Text = "0";
        }

        private void cmdLuu_Click(object sender, EventArgs e)
        {
            try
            {
                PHIEU_CHUYEN_KHO oPCK = new PHIEU_CHUYEN_KHO();
                oPCK.NgayXuat = DateTime.Today;
                oPCK.NguoiXuat = _nguoitao;
                oPCK.PlantReferenceSAP = _plant;

                if (lstCK.Count > 0)
                {
                    clsPHIEU_CHUYEN_KHO pckCtrl = new clsPHIEU_CHUYEN_KHO(_sConn);
                    string maphieuchuyenkho = pckCtrl.InsertPHIEU_CHUYEN_KHO(oPCK, lstCK, _matau);
                    if (maphieuchuyenkho != "")
                    {
                        this.txtSoPhieuCK.Text = maphieuchuyenkho;
                        this.lstCK.Clear();
                    }
                    else
                        MessageBox.Show("LƯU DỮ LIỆU KHÔNG THÀNH CÔNG");
                }
            }
            catch { }
        }

        private void gridDSVT_Click(object sender, EventArgs e)
        {
            GridView view = (GridView)sender;
            GridHitInfo info = view.CalcHitInfo(gridControl1.PointToClient(MousePosition));

            if (info.InRow || info.InRowCell)
            {
                this.cmdThemDS.Enabled = false;

                this.txtMaVTPT.Text = lstCK[info.RowHandle].MaThietBi;
                this.lblTenVTPT.Text = lstCK[info.RowHandle].TenVTPT;
                this.txtSoLuong.Text = lstCK[info.RowHandle].SoLuong.ToString();

                this.InitKho(this.txtMaVTPT.Text);
                this.InitTrangthai(this.txtMaVTPT.Text, lstCK[info.RowHandle].MaKhoNguon);

                this.lookUpKho.ItemIndex = this.lookUpKho.Properties.GetDataSourceRowIndex("MaKho", lstCK[info.RowHandle].MaKhoNguon);
                this.lookUpTrangthai.ItemIndex = this.lookUpTrangthai.Properties.GetDataSourceRowIndex("MaTrangThai", lstCK[info.RowHandle].MaTrangThai);
                this.lookUpKhoDich.ItemIndex = this.lookUpKhoDich.Properties.GetDataSourceRowIndex("MaKho", lstCK[info.RowHandle].MaKhoDich);

                float soluongmax = 0;
                clsTON_KHO tonCtrl = new clsTON_KHO(_sConn);
                List<TON_KHO> lstton = new List<TON_KHO>();
                lstton = tonCtrl.usp_SelectTON_KHO_ByMaKho(lstCK[info.RowHandle].MaKhoNguon, this.txtMaVTPT.Text, lstCK[info.RowHandle].MaTrangThai, null, null);
                for (int i = 0; i < lstton.Count; i++)
                {
                    soluongmax += lstton[i].SoLuong;
                }
                string makho = this.lookUpKho.GetColumnValue("MaKho").ToString();
                string makhodich = this.lookUpKhoDich.GetColumnValue("MaKho").ToString();
                int matrangthai = int.Parse(this.lookUpTrangthai.GetColumnValue("MaTrangThai").ToString().Trim());
                // kiem tra xem VTPT nay co cac phieu xuat kho nao chua duoc duyet
                List<CHI_TIET_PXH> lstctpxh = new List<CHI_TIET_PXH>();
                clsCHI_TIET_PXH ctpxhCtrl = new clsCHI_TIET_PXH(_sConn);
                lstctpxh = ctpxhCtrl.usp_CheckSoLuongXuatKhoChuaDuyet(this.txtMaVTPT.Text, lstCK[info.RowHandle].MaKhoNguon, lstCK[info.RowHandle].MaTrangThai);
                for (int i = 0; i < lstctpxh.Count; i++)
                {
                    soluongmax -= lstctpxh[i].SoLuong;
                }
                // kiem tra xem VTPT nay da ton tai trong list can chuyen kho chua
                for (int i = 0; i < lstCK.Count; i++)
                {
                    if (i != info.RowHandle)
                        if (lstCK[i].MaThietBi == this.txtMaVTPT.Text && lstCK[i].MaKhoNguon == makho && lstCK[i].MaTrangThai == matrangthai)
                            soluongmax -= lstCK[i].SoLuong;
                }

                this.lblsoluongton.Text = soluongmax.ToString();
            }
        }

        private void cmdCapNhatSL_Click(object sender, EventArgs e)
        {
            try
            {
                if (gridDSVT.FocusedRowHandle >= 0)
                {
                    int soluongxuat = int.Parse(this.txtSoLuong.Text.Trim());
                    int soluongton = int.Parse(this.lblsoluongton.Text);
                    string matrangthai = this.lookUpTrangthai.GetColumnValue("MaTrangThai").ToString();
                    string khonguon = this.lookUpKho.GetColumnValue("MaKho").ToString();
                    string khodich = this.lookUpKhoDich.GetColumnValue("MaKho").ToString();

                    if (soluongxuat <= 0)
                    {
                        MessageBox.Show("VUI LÒNG NHẬP SỐ LƯỢNG > 0");
                        return;
                    }

                    if (khonguon == khodich)
                    {
                        MessageBox.Show("KHO ĐÍCH PHẢI KHÁC KHO NGUỒN");
                        return;
                    }

                    if (soluongxuat > soluongton)
                    {
                        MessageBox.Show("VUI LÒNG NHẬP SỐ LƯỢNG CHUYỂN KHO <= " + this.lblsoluongton.Text);
                        return;
                    }

                    if (matrangthai != "-1" && lstCK[gridDSVT.FocusedRowHandle].MaThietBi == this.txtMaVTPT.Text)
                    {
                        lstCK[gridDSVT.FocusedRowHandle].SoLuong = int.Parse(this.txtSoLuong.Text);
                        lstCK[gridDSVT.FocusedRowHandle].MaKhoNguon = khonguon;
                        lstCK[gridDSVT.FocusedRowHandle].MaKhoDich = khodich;
                        lstCK[gridDSVT.FocusedRowHandle].MaTrangThai = int.Parse(this.lookUpTrangthai.GetColumnValue("MaTrangThai").ToString());
                        lstCK[gridDSVT.FocusedRowHandle].TenTrangThai = this.lookUpTrangthai.GetColumnValue("TenTrangThai").ToString();

                        this.gridControl1.RefreshDataSource();
                    }

                }
                else
                    MessageBox.Show("Vui lòng chọn dòng có VTPT cần thay đổi thông tin ");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void frmTaoPhieuCK_Paint(object sender, PaintEventArgs e)
        {
            // Common.PaintGradientColor(Color.LightYellow, Color.LightSkyBlue, System.Drawing.Drawing2D.LinearGradientMode.Vertical, this.Width, this.Height, this);            
        }

        private void tìmTheoNhiềuTiêuChíToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (frm == null)
            {
                frm = new frmTimKiemVTPT(_sConn,true);
                frm.SelectLstMaterial += new frmTimKiemVTPT.SelectListMaterialHandler(LuuDSVTPT);
            }
            else
                lstVTPT.Clear();
           
            frm.ShowDialog();
            if (lstVTPT.Count > 0)
            {
                if (lstVTPT.Count == 1)
                {
                    this.txtMaVTPT.Text = lstVTPT[0]._maVTPT;
                    this.lblTenVTPT.Text = lstVTPT[0]._tenVTPT;
                }
                else
                    MessageBox.Show("VUI LÒNG CHỌN TỪNG MỘT VTPT ĐỂ CHUYỂN KHO");
            }
        }

        private void tìmTheoHìnhToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (frm1 == null)
            {
                frm1 = new frmTimKiemTheoHinh(_sConn,true);
                frm1.SelectLstMaterialByImg += new frmTimKiemTheoHinh.SelectListMaterialByImgHandler(LuuDSVTPT);
            }
            else
                lstVTPT.Clear();
            frm1.ShowDialog();
            if (lstVTPT.Count > 0)
            {
                if (lstVTPT.Count == 1)
                {
                    this.txtMaVTPT.Text = lstVTPT[0]._maVTPT;
                    this.lblTenVTPT.Text = lstVTPT[0]._tenVTPT;
                }
                else
                    MessageBox.Show("VUI LÒNG CHỌN TỪNG MỘT VTPT ĐỂ CHUYỂN KHO");
            }
        }

        private void frmTaoPhieuCK_Load(object sender, EventArgs e)
        {
            Common.SetColor(this);
        }

        private void cmdXoaVTPT_Click(object sender, EventArgs e)
        {
            try
            {
                if (gridDSVT.FocusedRowHandle >= 0)
                {
                    if (MessageBox.Show("Bạn có thật sứ muốn XÓA ?", "Thông báo", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        lstCK.RemoveAt(gridDSVT.FocusedRowHandle);
                    }
                }
                this.gridControl1.RefreshDataSource();
            }
            catch { }
        }

        private void tìmVTIMPATheoNhiềuTiêuChíToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (frm2 == null)
            {
                frm2 = new frmImpa_TimKiem(_sConn,true);
                frm2.SelectLstMaterial += new frmImpa_TimKiem.SelectListMaterialHandler(LuuDSVTPT);
            }
            else
                lstVTPT.Clear();
            frm2.ShowDialog();
            if (lstVTPT.Count > 0)
            {
                if (lstVTPT.Count == 1)
                {
                    this.txtMaVTPT.Text = lstVTPT[0]._maVTPT;
                    this.lblTenVTPT.Text = lstVTPT[0]._tenVTPT;
                }
                else
                    MessageBox.Show("VUI LÒNG CHỌN TỪNG MỘT VTPT ĐỂ CHUYỂN KHO");

            }
        }

        private void tìmVTIMPATheoHìnhToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (frm3 == null)
            {
                frm3 = new frmImpa_TimKiemTheoHinh(_sConn,true);
                frm3.SelectLstMaterial += new frmImpa_TimKiemTheoHinh.SelectListMaterialHandler(LuuDSVTPT);
            }
            else
                lstVTPT.Clear();
            frm3.ShowDialog();
            if (lstVTPT.Count > 0)
            {
                if (lstVTPT.Count == 1)
                {
                    this.txtMaVTPT.Text = lstVTPT[0]._maVTPT;
                    this.lblTenVTPT.Text = lstVTPT[0]._tenVTPT;
                }
                else
                    MessageBox.Show("VUI LÒNG CHỌN TỪNG MỘT VTPT ĐỂ CHUYỂN KHO");

            }
        }

    
        private void txtMaVTPT_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                // kiểm tra tồn tại của VTPT                   

                VAT_TU_PHU_TUNG obj = new VAT_TU_PHU_TUNG();

                clsVAT_TU_PHU_TUNG vtptCtrl = new clsVAT_TU_PHU_TUNG(_sConn);

                obj = vtptCtrl.SelectVAT_TU_PHU_TUNG(this.txtMaVTPT.Text.Trim(), frmDangNhap.objTau.maTau);
                if (obj != null && obj._maVTPT != "")
                {
                    this.lblTenVTPT.Text = obj._tenVTPT;
                    this.cmdCapNhatSL.Enabled = true;
                    this.cmdThemDS.Enabled = true;
                    this.cmdXoaVTPT.Enabled = true;
                }
                else
                {
                    this.cmdCapNhatSL.Enabled = false;
                    this.cmdThemDS.Enabled = false;
                    this.cmdXoaVTPT.Enabled = false;

                    MessageBox.Show("KHÔNG TÌM THẤY THÔNG TIN VẬT TƯ NÀY");
                }
            }
        }
    }
}